package org.jeecg.modules.iot.config.netty;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.util.SpringContextUtils;


@Slf4j
public class NettyServerHandler extends ChannelInboundHandlerAdapter {

    private ISysBaseAPI sysBaseAPI;
    /**
     * 客户端连接会触发
     */
    NettyServerHandler(){
        this.sysBaseAPI = SpringContextUtils.getBean(ISysBaseAPI.class);
    }
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        ctx.fireChannelActive();
        log.info("开启一个链接：" + ctx.name() + " " + ctx.channel().remoteAddress());
    }

    /**
     * 客户端发消息会触发
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        DeviceProtocol deviceProtocol = (DeviceProtocol)msg;
//        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String[] userIds = new String[]{"e9ca23d68d884d4ebb19d07889727dae"};
//        ISysBaseAPI sysBaseAPI = SpringContextUtils.getBean(ISysBaseAPI.class);
        sysBaseAPI.sendWebSocketMsg(userIds,"deviceProtocol.header");
        log.info("服务器收到消息: {}", deviceProtocol.getPayload());
//        log.info(String.valueOf(count++));
//        byte[] bytes = new byte[2];
//        bytes[0] =0x55;
//        bytes[1] = (byte) 0xf5;
//        DeviceProtocol.writeMessage(ctx,bytes);
    }

    /**
     * 发生异常触发
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        log.info("连接异常：" + ctx.name() + " " + ctx.channel().remoteAddress());
        ctx.close();
    }
}
